import axios from 'axios';
import { getItem, setItem, removeItem } from '../../utils/store';
import {sessionManager} from '../../utils/sessionStorage';

const LOGIN_SUCCESS = "LOGIN_SUCCESS";
const LOGOUT_SUCCESS = "LOGOUT_SUCCESS";
const SAVE_CODE="SAVE_CODE";
const locale=sessionManager.get('locale');

const initState = {
	redirectTo:'',
	token: '',
	username: '',
	password: '',
    jcaptcha:'',
    verificationCode:'',
    locale:''
}

// reducer
export function auth(state=initState, action) {
	switch(action.type) {
		case LOGIN_SUCCESS:
			return {...state, password:'', redirectTo:'/', ...action.payload,locale:locale};
		case LOGOUT_SUCCESS:
			return {...state, token:'', redirectTo:'newLogin'};
		case SAVE_CODE:
			return {...state,...action.payload};
		default:
			return state;
	}
}

// action creator
function login(data) {
	return {type:LOGIN_SUCCESS, payload:data};
}

function logout() {
	return {type:LOGOUT_SUCCESS};
}

function saveCode(data) {
	return {type:SAVE_CODE, payload:data}
}

// 登录操作
export function actionLogin({username,password,verificationCode}) {
	// console.log(username,password,verificationCode)
	return dispatch => {
        axios.post('/api/admin/login', {
            account:username,
            password:password,
            jcaptcha:verificationCode,
        }).then(res => {
			if (res && res.data) {
                // 把用户信息存入store
                console.log(res);
                setItem('token', JSON.stringify(res.data));
				dispatch(login({username,...res.data}));
			}else{
                axios.post('/api/admin/corp/jcaptcha', {
                }).then(res => {
                    if(res&&res.data){
                        dispatch(saveCode({verificationCode:res.data}))
                    }
                })
			}
		})
	}
}

// 登出操作
export function actionLogout() {
    return dispatch => {
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        const userInfo = JSON.parse(getItem("token"));
        if (userInfo) {
            axios.post('/api/user/logout', {
                token: userInfo.token
            }).then(res => {
                removeItem('token');
            });
        }
        dispatch(logout());
    }
}

// 登出操作
export function apiLogout() {
    return dispatch => {
        // 判断是否存在token，如果存在的话，则每个http header都加上token
        dispatch(logout());
    }
}